import React, { Fragment } from 'react'
import ReactDOM from 'react-dom'

function ReactApp({store, router, render}) {
    this.MOUNT_NODE = null
    let ComposedApp = null

    const mount = (App, selector) => {
        if (!selector) {
            selector = App
            App = Fragment
        }
        store.addModule('router', router.module)
        if (!store.initialized) {
            store.init()
        }
        this.MOUNT_NODE = document.querySelector(selector)

        /**
         * React开起严格模式后在开发模式下会，触发两次router的action
         * 生产模式下不会有这个问题，所以严格模式是可选的
         **/ 
        ComposedApp = () => (
            <store.Provider store={store}>
                <router.ConnectedRouter history={router.history}>
                <App>
                    <router.Routes></router.Routes>
                </App>
                </router.ConnectedRouter>
            </store.Provider>
        )
        ReactDOM.render(<ComposedApp></ComposedApp> ,this.MOUNT_NODE)
    }
    if (typeof render === 'function') {
        render(mount)
    }

    this.mount = mount

    this.unmount = () => {
        ReactDOM.unmountComponentAtNode(this.MOUNT_NODE)
    }

    const restart = () => {
        this.unmount()
        ReactDOM.render(<ComposedApp></ComposedApp> ,this.MOUNT_NODE)
    }

    this.restart = restart
    this.reboot = restart
}

export default ReactApp